from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.forms import StartGroupForm, StartGroupFormNoMember, GroupPortraitForm
from contifyuser.models import Member
from django.contrib.auth.models import User
from StartGroup.models import Group, GroupPortrait
from groupMembers.models import Member_Group, group_mem_assoc_v
from groupevents.models  import Events
import Constants
import connectpeople.Constants
from datetime import datetime
import simplejson
from django.http import HttpResponse
import utils.signals
from utils import common_query, common_methods, activity_module
import threading
from operator import attrgetter
from groupInfo.models import Info
from announcement.models import Announcement


# render form for starting a new group
def startNewGroupForm(request):
    
    render_template = Constants.start_group
    
    # Get User id from session
    if connectpeople.Constants.session_userid in request.session:
        # user is signed in
        userid = request.session[connectpeople.Constants.session_userid]
        # get member from group_mem_assoc_v
        member = common_query.get_group_member(userid, False)
        # Start Group form initialization
        start_group_form = StartGroupForm()
        signin_form = ''
        render_template += Constants.group_form_authenticated_template
        
    else:
        # User is not signed in
        member = ''
        # Start Group form initialization
        start_group_form = StartGroupFormNoMember()
        signin_form = AuthenticationForm()
        render_template += Constants.group_form_not_authenticated_template
    
    # Send response
    return render_to_response(render_template,
                              {Constants.start_group_form_constant: start_group_form,
                                connectpeople.Constants.signin_form_constant: signin_form,
                                Constants.member_constant: member},
                              context_instance = RequestContext(request))
    
def startNewGroup(request):
    
    # Form validation flag
    form_validated = False
        
    if connectpeople.Constants.session_userid in request.session:
        # User is signed in
        userid = request.session[connectpeople.Constants.session_userid]
        user = User.objects.get(username=userid)
        member = Member.objects.get(user=user)
        if request.method == 'POST':            
            # Start Group Authenticated form initialization
            start_group_form = StartGroupForm(data=request.POST)

            if start_group_form.is_valid():
                form_validated = True
                group = start_group_form.save(member)
                mem_grp_obj = Member_Group(group_id=group.id, user_id=userid, join_date=datetime.now(), group_web_address=group.group_web_address, permission=connectpeople.Constants.owner)
                mem_grp_obj.save()
                # Renew user data with updated values
                member_data = common_query.get_group_member(userid, True)
                    
                # Check if user wants to get the email update
                should_email = common_methods.getEmailFlag(member_data[0].email_setting, connectpeople.Constants.new_group_email_flag_constant)
                if should_email == "1":
                    #Email parameters
                    # Get email ids of the user
                    recipient = []
                    recipient.append(member_data[0].email)
                    # Compose subject for the email
                    subj = request.POST.__getitem__('group_name') +  " - New ConnectPeople Group Created"
                    # name of the recipeint
                    rec_name = member_data[0].first_name
                    
                    # Send Email. Use threading                    
                    new_group_thread= threading.Thread(target=common_methods.send_single_email_helper, kwargs={'a_sender':Group, 'a_email':recipient, 'a_name':rec_name, 'a_model':group, 'a_subject':subj, 'a_template':"email/newGroupEmail.html"})
                    new_group_thread.setDaemon(True)
                    new_group_thread.start()
            else:
                # If form is not valid then redirect to same page
                render_template = "StartGroup/group_form2.html"
                signin_form = ''
    else:
        # User is not signed in
        member = ''
        if request.method == 'POST':
            # Start Group form initialization
            start_group_form = StartGroupFormNoMember(data=request.POST)
            
            if start_group_form.is_valid():
                form_validated = True
                
                group = start_group_form.save()
                username = group.member_user.user.username
                mem_grp_obj = Member_Group(group_id=group.id, user_id=username, join_date=datetime.now(), group_web_address=group.group_web_address, permission=connectpeople.Constants.owner)
                mem_grp_obj.save()                
                # Renew user data with updated values
                member = common_query.get_group_member(username, True)
                
                #Email parameters
                # Get email ids of these users
                recipient = []
                recipient = recipient.append(request.POST.__getitem__('email'))
                print request.POST
                # Compose subject for the email
                subj = request.POST.__getitem__('group_name') +  " - New ConnectPeople Group Created"
                # name of the recipeint
                rec_name = request.POST.__getitem__('first_name')
                
                # Send Email. Use threading
                new_group_thread= threading.Thread(target=common_methods.send_single_email_helper, kwargs={'a_sender':Group, 'a_email':recipient, 'a_name':rec_name, 'a_model':group, 'a_subject':subj, 'a_template':"email/newGroupEmail.html"})
                new_group_thread.setDaemon(True)
                new_group_thread.start()                
                
            else:
                # If form is not valid then redirect to same page
                render_template = "StartGroup/group_form1.html"
                
                # If user is not signed in then show sign_in form
                signin_form = AuthenticationForm()
        
    if form_validated:
        render_template = "StartGroup/group_complete.html"
        return render_to_response(render_template,
                              {Constants.start_group_form_constant: start_group_form,
                                Constants.member_constant: member},
                              context_instance = RequestContext(request))
    else:
        return render_to_response(render_template,
                              {Constants.start_group_form_constant: start_group_form,
                                connectpeople.Constants.signin_form_constant: signin_form,
                                Constants.member_constant: member},
                              context_instance = RequestContext(request))
    
def group_view(request, group_web_address):
    
    if 'event_id' in request.session:
        # delete event id from session
        del request.session['event_id']

    if request.method == 'POST':
        try:
            action = request.POST.__getitem__('action')
        except:
            action = None
            
        if action == "GROUP_PORTRAIT_UPLOAD":
            port_form = GroupPortraitForm(files=request.FILES)
            print request.FILES
            
            if port_form.is_valid():
                port_form.save(group_web_address)
        else:
            # Get the comment id to be deleted
            eveid = request.POST.__getitem__('eveid')
                
            if eveid:
                # Delete the event from database
                Events.objects.get(id=eveid).delete()
                # Set response to success
                response = simplejson.dumps({'success':'success'})
            
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
                
    # Store group in session:
    #request.session[connectpeople.Constants.session_group_web_address] = group_web_address
    group = getGroupFromWebAddr(group_web_address)
    # Upcoming group events list
    up_group_events = getEvents(group_web_address, Constants.up_group_events)
    up_group_event_list = getEventsInList(up_group_events)
    
    # Previous group events list
    prev_group_events = getEvents(group_web_address, Constants.prev_group_events)
    prev_group_event_list = getEventsInList(prev_group_events)
    
    # Obtain user id
    userid = request.session[connectpeople.Constants.session_userid]

    # Prepare sub list of group members
    mem_grp_data = common_query.get_member_from_gwebaddr(group_web_address, False)
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_address, False)
    
    # Get Activities related to user
    activity_dict = activity_module.getGroupActivities([group])
    
    # Group Portrait Form
    portrait_form = GroupPortraitForm()
    
    # Get group portrait
    try:
        portrait = GroupPortrait.objects.get(group = group_web_address)
    except:
        portrait = None
        
    # Get Recent Announcements
    announcements = Announcement.objects.filter(group= group_web_address).order_by('-created_date')[:5]
    
    # Get Info
    group_information = getInfo(group)
    print group_information
    return render_to_response(Constants.start_group + Constants.group_home_template,
                              {Constants.group_constant: group, 'up_group_event_list': up_group_event_list,
                               'prev_group_event_list': prev_group_event_list,
                               'mem_grp_data': mem_grp_data, 'permission':permission,
                               'activity_dict':activity_dict, 'portrait_form': portrait_form,'portrait':portrait,
                               'group_information':group_information, 'userid':userid,'announcements':announcements},
                              context_instance = RequestContext(request))


# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)

# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)
    
# Helper function to obtain grou info from group web address
def getGroupFromWebAddr(group_web_addr):
    return Group.objects.get(group_web_address=group_web_addr)


# Helper function to obtain Events associated with the group
def getEvents(group_web_addr, date_filter):
    
    if date_filter == Constants.up_group_events:
        return Events.objects.filter(group=group_web_addr).filter(event_date__gt = datetime.now()).order_by('-event_date')
    elif date_filter == Constants.prev_group_events:
        return Events.objects.filter(group=group_web_addr).filter(event_date__lte = datetime.now()).order_by('-event_date')
    else:
        return Events.objects.filter(group=group_web_addr)

# Helper function to obtain Events in a list format
def getEventsInList(group_events):
    group_event_list = []
    if group_events is not None:
        for each in group_events:
            group_event_list.append(each)
    
    return group_event_list

def getInfo(group_info):
    try:
        return Info.objects.get(group=group_info)
    except:
        return None